開始玩 Go Concurrent 部分,最好還是先 channel & select 先弄清楚點。
Channel
初始狀況為 nil。
Channel Type
可以設定為 send only receive only & 雙向
1 | chan T // 雙向 |
特殊狀況一 nil channel
對一個 nil channel 傳送 或 接收會照成永久 block
1 | <- nilCH |
特殊狀況二 closed channel
對 closed channel 傳送資料會造成 run-time Panic
1 | closedCh <- 1 // run-time Panic |
對 closed channel 接收資料會得到 zero value
1 | package main |
select
For all the cases in the statement,
the channel operands of receive operations and the channel and right-hand-side expressions of send statements are evaluated exactly once,
in source order, upon entering the “select” statement.如果有一個以上的 communications 可以執行,則隨機取一
如果沒有可以執行的 communication,但有default,則選default
如果連default都沒有的話,select 會等到其中一個 communication 可以執行- def
- 如果選了接收的 case,左手方會被賦值
- The statement list of the selected case is executed.
select 只有 nil channel 且沒 default 則會 block forever